<?php
/**
 * Created by PhpStorm.
 * User: Heido
 * Date: 2019/10/15
 * Time: 16:25
 */

namespace app\common\controller;


use app\admin\traits\Result;
use think\Controller;
use think\facade\Env;
use think\facade\Request;
use think\Image;

class Upload extends Controller
{

    public function uploadImage($thumb_config = ['small' => 100, 'medium' => 500, 'big' => 1000])
    {
        //request()->file()是针对表单提交的上传文件，如果使用ajax的话，是获取不到的
        $file = Request::file('file');

        $sha1 = $file->hash();
        $picture_info = \app\common\model\Upload::getInfo(['sha1' => $sha1]);

        if (!empty($picture_info)) {

            return Result::success('上传成功', '', $picture_info);
        } else {
            $path = Env::get('root_path') . '/public/upload/picture';
            //检查上传图片
            $info = $file->validate(['size' => 15678, 'ext' => 'jpg,png,gif'])->move($path);

            if ($info) {
                $save_name = $info->getSaveName();

                $save_path = $path . $save_name;

                //得到以日期命名的目录
                $picture_dir_name = substr($save_name, 0, strrpos($save_name, DIRECTORY_SEPARATOR));

                //得到新文件名
                $filename = $info->getFilename();


                $data = ['name' => $filename, 'path' => $picture_dir_name . '/' . $filename, 'sha1' => $sha1];

                $picture = new \app\common\model\Upload();
                $result = $picture->setInfo($data);

                if ($result) {
                    $picture_info = \app\common\model\Upload::getInfo(['sha1' => $sha1]);
                    return Result::success('上传成功', '', $picture_info);
                }
            } else {
                // 上传失败获取错误信息
                return Result::error('上传失败', '', $file->getError());
            }
        }
    }

}